package com.example.demo.controller;


import com.example.demo.entity.Userinfo;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/get-user-id")
    public Userinfo getUserById(Integer id) {
        if (id == null)
            return null;
        return userService.getUserById(id);
        // url: http://localhost:8080/user/get-user-id?id=1
        // 预期结果: {"id":1,"username":"admin","password":"admin","photo":"",
        //          "createtime":"2021-12-06T17:10:48","updatetime":"2021-12-06T17:10:48","state":1}
    }

    // 查询所有用户
    @RequestMapping("/getalluser")
    public List<Userinfo> getAll() {
        return userService.getAll();
        // url: http://localhost:8080/user/getalluser
    }

    // 增
    @PostMapping("/getinsertid")
    // @RequestBody 表示从 Json 的 body 读取数据.
    public int insertGetId(@RequestBody Userinfo userinfo) {
        userService.insertGetId(userinfo);
        return userinfo.getId();
        // url: http://localhost:8080/user/getinsertid
    }

    // 改
    @RequestMapping("/upusername")
    public String updateUserName(@RequestBody Userinfo userinfo) {
        int result = userService.updateUserName(userinfo);
        return result + " row affected";
        // url: http://localhost:8080/user/upusername
    }

    // 删
    @RequestMapping("/deluserbyid")
    public String delUserById(Integer id) {
        int result = userService.deleteUserById(id);
        return result + " row affected";
        // url: http://localhost:8080/user/deluserbyid?id=9
    }
}
